package com.jplus.plugins.rpc.impl.handler.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.jplus.framework.bean.annotation.Component;
import com.jplus.framework.mvc.DataContext;
import com.jplus.framework.mvc.action.Handler;
import com.jplus.framework.mvc.handler.param.IWatcher;
import com.jplus.framework.mvc.handler.param.ParamWatcher;
import com.jplus.plugins.rpc.annotation.RpcProvider;

/**
 * 入参观察者
 * 
 * @author Yuanqy
 */
@Component(initMethod = "init")
public class HttpParamWatcher implements IWatcher {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public List<Object> getParams(Handler handler) throws Exception {
		Class<?>[] ptypes = handler.getActionMethod().getParameterTypes();
		if (ptypes.length == 0)
			return null;
		Class<?> action = handler.getActionClass();
		if (action.isAnnotationPresent(RpcProvider.class)) {
			logger.info(">>>Coming a RPC request[{}]:{},{}", "Http", handler.getActionClass().getName(), handler.getActionMethod().getName());
			HttpServletRequest req = DataContext.getRequest();
			try {
				ServletInputStream is = req.getInputStream();
				BufferedReader in = new BufferedReader(new InputStreamReader(is));
				StringBuffer buffer = new StringBuffer();
				String line = "";
				while ((line = in.readLine()) != null) {
					buffer.append(line);
				}
				String request = buffer.toString();
				List<Object> list = JSON.parseArray(request);
				Object[] obj = new Object[list.size()];
				for (int i = 0; i < list.size(); i++) {
					obj[i] = JSON.parseObject(list.get(i).toString(), ptypes[i]);
				}
				return Arrays.asList(obj);
			} catch (Exception e) {
				throw e;
			}
		}
		return null;
	}

	/**
	 * 添加观察
	 */
	public void init() {
		if (HttpService.ai.get() > 0)
			ParamWatcher.addWatcher(this);
	}
}
